/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MNetSockets.DataChanel;

import MNetSockets.CmdChanel.CmdClient;
import MNetSockets.CmdChanel.CmdRun;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 *       @author wcss
 */
public class UDPDataRun implements Runnable {

    public DataClient client = null;

    public UDPDataRun(DataClient c) {
        this.client = c;
    }

    @Override
    public void run() {
        StringBuilder sb = new StringBuilder();
        String cont = null;
        int flagindex = 0;
        int beginindex = 0;
        QueueObject current = null;
        while (this.client.isRun) {
            try {
                beginindex = 0;
                flagindex = sb.indexOf(DataClient.udpDataEndFlag);
                if (flagindex > 0 && beginindex >= 0) {
                    sb.delete(0, beginindex);
                    sb.trimToSize();
                    flagindex = sb.indexOf(DataClient.udpDataEndFlag);
                    cont = sb.substring(0, flagindex + DataClient.udpDataEndFlag.trim().length());
                    sb.delete(0, flagindex + DataClient.udpDataEndFlag.trim().length());
                    sb.trimToSize();
                    this.client.handleUDPDataRead(current.getAddress(), cont.trim().replace(DataClient.udpDataEndFlag, ""));
                } else {
//                    if (sb.length() > 0) {
//                        System.out.println("Data Format Is Error! Buffer Clear!");
//                    }
                    if (sb.length() > 0) {
                        sb.delete(0, sb.length() - 1);
                        sb.trimToSize();
                    }
                }

                if (this.client.queue.size() > 0) {
                    current = this.client.queue.poll();
                    sb.append(current.getData());
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }

            try {
                Thread.sleep(50);
            } catch (InterruptedException ex) {
                Logger.getLogger(CmdRun.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
